package com.appspot.gaeforum309.db;

import java.util.List;

import javax.jdo.Query;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;

@PersistenceCapable
public class DBConfig {
	@PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Key key;
	
	@Persistent
	private String param;
	
	@Persistent
	private String value;
	
	
	public DBConfig(String param, String value) {
		super();
		this.param = param;
		this.value = value;
	}

	private static DBConfig getConfig(String param)
	{
		Query q = PMF.pm().newQuery(DBConfig.class);
		q.setFilter("param == argParam");
		q.declareParameters("String argParam");
		List<DBConfig> res = (List<DBConfig>) q.execute(param);
		
		if(res.size() == 0)
			return null;
		return res.get(0);
	}
	
	public static String getParam(String param, String defaultValue)
	{
		DBConfig dbconfig = getConfig(param);
		if(dbconfig == null)
		{
			setParam(param, defaultValue);
			return param;
		}
		return dbconfig.value;					
	}
	
	public static void setParam(String param, String value)
	{
		DBConfig dbconfig = getConfig(param);
		if(dbconfig == null)
		{
			dbconfig=new DBConfig(param, value);
			PMF.pm().makePersistent(dbconfig);
			return;
		}
		else
		{
			dbconfig.value = value;
		}
	}
	
	public static boolean removeParam(String param)
	{
		DBConfig dbconfig = getConfig(param);
		if(dbconfig == null)
			return false;
		
		PMF.pm().removeUserObject(dbconfig);
		return true;
	}
}
